package com.xxx.service.impl;

import com.xxx.pojo.Department;
import com.xxx.mapper.DepartmentMapper;
import com.xxx.pojo.RespBean;
import com.xxx.service.IDepartmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WXH
 * @since 2022-02-23
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements IDepartmentService {

    @Autowired
    DepartmentMapper departmentMapper;
    /**
     * 获取所有部门列表
     * @param deptId
     * @return
     */
    @Override
    public List<Department> getAllInFo(Integer deptId) {
        // 通过部门主键id，查询该部门下的所有子部门，子部门的父id就是当前该部门的主键id
       List<Department> allInFo= departmentMapper.getAllInFo(deptId);
        // 遍历该部门下的子部门
        for (Department department : allInFo) {
            // 子部门的id
            Integer id = department.getId();
            // 递归，用子部门的主键id，查询该部门下的子部门
            List<Department> sonDepartment = getAllInFo(id);
            // 设置当前子部门的子节点
            department.setChildren(sonDepartment);
        }
        return allInFo;

    }
    /**
     * 添加部门
     * @param department
     * @return
     */
    @Override
    public int add(Department department) {
        return departmentMapper.add(department);
    }
    /**
     * 添加部门
     * @param department
     * @return
     */
    @Override
    public RespBean addDept(Department department) {
        department.setEnabled(true);
        departmentMapper.addDept(department);
        if (department.getResult() == 1){
            return RespBean.sucess("添加成功！！！",department);
        }
        return RespBean.error("添加失败");
    }
    /**
     * 删除部门
     * @param id
     * @return
     */
    @Override
    public RespBean deleteDept(Integer id) {
        Department department = new Department();
        department.setId(id);
        departmentMapper.deleteDept(department);
        if(department.getResult() == -2) return RespBean.error("该部门下还有子部门，删除失败");
        if(department.getResult() == -1) return RespBean.error("该部门下还有员工，删除失败");
        if(department.getResult() == 1) return RespBean.sucess("删除成功");
        return RespBean.error("删除失败");

    }
}
